package com.hfzy.ihk.web.userCenter.controller;


import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.facade.userCenter.entity.Resource;
import com.hfzy.ihk.facade.userCenter.entity.UserInfo;
import com.hfzy.ihk.web.oauth.client.utils.UserUtil;
import com.hfzy.ihk.web.userCenter.biz.ResourceBiz;
import com.hfzy.ihk.web.userCenter.mapper.ResourceMapper;
import com.hfzy.ihk.web.userCenter.vo.MenuVo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>
 * 用于集成spring security,权限表 前端控制器
 * </p>
 *
 * @author chenzesen
 * @since 2018-12-28
 */
@RestController
@RequestMapping("resource")
@Slf4j
public class ResourceController {


    @Autowired
    ResourceMapper resourceMapper ;

    @Autowired
    ResourceBiz resourceBiz;

    private static final Logger logger = LoggerFactory.getLogger(ResourceController.class);

    @RequestMapping(value = {"/list"})
    public ModelAndView list(HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView) {
        modelAndView.setViewName("page/resource/resourceList");
        return modelAndView;
    }



    @RequestMapping(value = {"/addPage"})
    public ModelAndView addPage(HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView,String parentId,String parentName) {
        if(parentId!=null&&!parentId.equals("")){
            modelAndView.addObject("parentId",parentId);
        }else{
            modelAndView.addObject("parentId",null);
        }
        if(parentName!=null&&!parentName.equals("")){
            modelAndView.addObject("parentName",parentName);
        }else{
            modelAndView.addObject("parentName",null);
        }
        modelAndView.setViewName("page/resource/addResource");
        return modelAndView;
    }

    @RequestMapping(value = {"/updatePage"})
    public ModelAndView updatePage(HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView,Long id) {
        modelAndView.setViewName("page/resource/updateResource");
        modelAndView.addObject("id",id);
        Resource resource = resourceMapper.getById(id);
        modelAndView.addObject("resource",resource);
        return modelAndView;
    }


    /**
     * 菜单列表
     * @return
     */
    @RequestMapping("resourceList")
    public Map<String,Object> newPermissionsList() {
        Map<String,Object> map = new HashMap<>();
        List<Resource> permissionsAll = resourceMapper.listAll();
        List<Resource> list = new ArrayList<>();
        setPermissionsList(0, permissionsAll, list);
        map.put("msg","");
        map.put("code","0");
        map.put("data", list);
        map.put("count", list.size());
        map.put("is", true);
        map.put("tip", "操作成功");
        return map;
    }


    /**
     * 设置菜单列表，
     *
     * @param pId
     * @param resourceAll
     * @param list
     */
    private void setPermissionsList(Integer pId, List<Resource> resourceAll, List<Resource> list) {
        for (Resource per : resourceAll) {
            if (per.getParentId().equals(pId)) {
                if(StringTools.isEmpty(per.getUri())&&"1".equals(per.getType())){
                    per.setLay_is_open(true);
                }else{
                    per.setLay_is_open(false);
                }
                list.add(per);
                if (resourceAll.stream().filter(p -> p.getParentId().equals(per.getId())).findAny() != null) {
                    setPermissionsList(per.getId(), resourceAll, list);
                }
            }
        }
    }


    /**
     * 所有父级菜单
     * @return
     */
    @RequestMapping("parents")
    public List<Resource> parentMenu() {
        List<Resource> parents = resourceMapper.listParents();

        return parents;
    }


    /**
     * 更新菜单
     * @param resource
     * @return
     */
    @RequestMapping("update")
    public Map<String,Object> update( Resource resource) {
        Map<String,Object> map = new HashMap<>();
        try {
            Resource re = resourceMapper.getResourceByName(resource.getLabel());
            if(re!=null&&re.getId()!=resource.getId())
            {
                map.put("code",0);
                map.put("msg","已存在该菜单名");
                return map;
            }
            //判断按钮权限名称是否存在
            if(resource.getType().equals("2")){
                Resource r = resourceMapper.getResourceBybtnPremissionName(resource.getBtnPermission());
                if(r!=null&&r.getId()!=resource.getId())
                {
                    map.put("code",0);
                    map.put("msg","已存在该按钮权限");
                    return map;
                }

            }
            UserInfo userInfo = UserUtil.getLoginUser();
            if(userInfo!=null){
                resource.setModTime(new Date());
                resource.setModUserId(userInfo.getId());
            }
            resourceMapper.updateById(resource);
           // resourceMapper.update(resource);
            map.put("code",1);
            map.put("msg","保存成功");
        }catch (Exception e){
            map.put("code",0);
            map.put("msg","保存失败");
            logger.error("保存菜单错误！",e);
        }
        return map;

    }

    /**
     * 保存菜单
     * @param resource
     * @return
     */
    @RequestMapping("save")
    public Map<String,Object> save( Resource resource) {
        Map<String,Object> map = new HashMap<>();

        try {
            Resource re = resourceMapper.getResourceByName(resource.getLabel());
            if(re!=null){
                map.put("code",0);
                map.put("msg","已存在该菜单名");
                return map;
            }
            //判断按钮权限名称是否存在
            if(resource.getType().equals("2")){
                Resource r = resourceMapper.getResourceBybtnPremissionName(resource.getBtnPermission());
                if(r!=null)
                {
                    map.put("code",0);
                    map.put("msg","已存在该按钮权限");
                    return map;
                }

            }

            UserInfo userInfo = UserUtil.getLoginUser();
            if(userInfo!=null)
            resource.setCreateUserId(userInfo.getId());
            resource.setCreateTime(new Date());
            resource.setEnabled(true);
            resourceMapper.insert(resource);
            //resourceMapper.save(resource);
            map.put("code",1);
            map.put("msg","保存成功");
        }catch (Exception e){
            map.put("code",0);
            map.put("msg","保存失败");
            logger.error("保存菜单错误！",e);
        }
        return map;
    }


    /**
     * 删除resource 的时候同事删除所有的关系
     * @param id
     */
    @RequestMapping("/delete/{id}")
    public void delete(@PathVariable Long id) {
        resourceBiz.deleteResource(id);
    }

    /**
     * 打开查看菜单权限页
     * @param request
     * @param response
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = {"/showPriv"})
    public ModelAndView showPriv(HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView,String userId,String id) {
        modelAndView.setViewName("page/resource/showResource");
        modelAndView.addObject("userId",userId);
        modelAndView.addObject("id",id);
        return modelAndView;
    }


    /**
     * 根据当前人的权限，获取最顶级菜单
     * @return
     */
    @RequestMapping("parentTopMenu")
    public List<Resource> parentTopMenu(){
        try {
            List<Resource> resourceList = resourceBiz.queryThisUserAllResource();
            if (resourceList == null) {
                return new ArrayList<Resource>();
            }
            return resourceList;
        }catch (IllegalArgumentException e){
            log.error(e.getMessage(),e);
            return new ArrayList<Resource>();

        }catch (Exception e1){
            log.error("获取顶部菜单失败",e1);
            return new ArrayList<Resource>();
        }

    }

    @RequestMapping("resourceByParentId")
    public List<MenuVo> resourceByParentId(Long parentId){

        return resourceBiz.resourceByParentId(parentId);
    }
}
